<script setup lang="ts">
import { ref, watch } from 'vue';
import { fetchJobDetail, updateJob } from '@/service/api';

defineOptions({
  name: 'DagDesignerModal'
});

interface Props {
  jobId?: number;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const loading = ref(false);
const dagConfig = ref('');
const jobData = ref<Api.Dataplatform.Job | null>(null);

async function loadJobData() {
  if (!props.jobId) return;

  loading.value = true;
  try {
    const { data, error } = await fetchJobDetail(props.jobId);
    if (!error && data) {
      jobData.value = data;
      dagConfig.value = data.dagConfig || '';
    }
  } finally {
    loading.value = false;
  }
}

async function handleSave() {
  if (!props.jobId || !jobData.value) return;

  loading.value = true;
  try {
    const { error } = await updateJob({
      id: props.jobId,
      name: jobData.value.name,
      jobType: jobData.value.jobType,
      dagConfig: dagConfig.value,
      scheduleType: jobData.value.scheduleType,
      scheduleConfig: jobData.value.scheduleConfig,
      status: jobData.value.status,
      projectId: jobData.value.projectId,
      description: jobData.value.description
    });

    if (!error) {
      window.$message?.success('保存成功');
      visible.value = false;
      emit('submitted');
    }
  } finally {
    loading.value = false;
  }
}

watch(visible, () => {
  if (visible.value) {
    dagConfig.value = '';
    jobData.value = null;
    loadJobData();
  }
});
</script>

<template>
  <NModal v-model:show="visible" preset="card" title="DAG 编排设计器" class="w-1200px">
    <NSpin :show="loading">
      <NAlert type="info" class="mb-4">
        <template #header>DAG 配置说明</template>
        请使用 JSON 格式配置任务依赖关系。示例：
        <NCode
          :code="
            JSON.stringify(
              {
                nodes: [
                  { id: 'task1', name: '任务1', type: 'ETL' },
                  { id: 'task2', name: '任务2', type: 'SQL' }
                ],
                edges: [{ source: 'task1', target: 'task2' }]
              },
              null,
              2
            )
          "
          language="json"
          class="mt-2"
        />
      </NAlert>

      <NFormItem label="DAG 配置 (JSON)">
        <NInput
          v-model:value="dagConfig"
          type="textarea"
          :rows="20"
          placeholder="请输入 DAG 配置 JSON"
          :disabled="loading"
        />
      </NFormItem>

      <NAlert type="warning" class="mt-4">
        注意：完整的可视化 DAG 编排器需要集成 AntV X6 图形库，当前版本提供 JSON 配置方式。
      </NAlert>
    </NSpin>

    <template #footer>
      <NSpace justify="end">
        <NButton @click="visible = false">取消</NButton>
        <NButton type="primary" :loading="loading" @click="handleSave">保存</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
